<template>
  <div class="confirm-weight">
    <div class="header">
      <div class="left">
        {{ numberToChinese(weightTime + 1) }}磅
        <img :src="typeImg" class="type-img" />
      </div>
      <img src="@/assets/img/fork.svg" class="right" @click="cancel" />
    </div>
    <div class="body">
      <div class="cus-msg">
        <div class="divide">
          <div class="border border-left"></div>
          <div class="txt">过磅人</div>
          <div class="border border-right"></div>
        </div>
        <div class="content">
          <img :src="file3" class="capture" v-if="form.type !== '4'" />
          <div class="msg first">
            <div class="row">
              <div class="label">
                <div class="red">*</div>
                姓名：
              </div>
              <input
                class="value"
                v-model="form.cusName"
                v-show="isRecognitionSuccessful"
                disabled
              />
              <input
                class="value"
                v-model="form.cusName"
                v-show="!isRecognitionSuccessful"
                @click="showSupplierSearch"
              />
            </div>
            <div class="row">
              <div class="label">手机号：</div>
              <input
                class="value"
                :value="form.cusMobile"
                v-show="isRecognitionSuccessful"
                disabled
              />
              <input class="value" v-model="form.cusMobile" v-show="!isRecognitionSuccessful" />
            </div>
            <div class="row" v-if="form.cusType === '2' && isRecognitionSuccessful">
              <div class="label">身份证：</div>
              <input class="value" :value="showIdCard" v-show="isRecognitionSuccessful" disabled />
            </div>
            <div class="row" v-if="!isRecognitionSuccessful">
              <div class="label">身份证：</div>
              <input class="value" v-model="form.cusIdCard" />
            </div>
            <div class="row" v-if="form.cusType === '1'">
              <div class="label">税号：</div>
              <input class="value" :value="form.cusTaxNum" disabled />
            </div>
          </div>
        </div>

        <div class="divide">
          <div class="border border-left"></div>
          <div class="txt">摄像头抓图</div>
          <div class="border border-right"></div>
        </div>
        <div class="capture-container">
          <img :src="file1" class="weight-pic" />
          <img :src="file2" class="weight-pic" />
        </div>
      </div>
      <div class="split"></div>
      <div class="other">
        <div class="divide">
          <div class="border border-left"></div>
          <div class="txt">过磅信息</div>
          <div class="border border-right"></div>
        </div>
        <div class="weight">
          <div class="row" v-if="inspectIndex === 2">
            <div>单号：</div>
            <div class="value no">{{ baseOrder.baseOrderNo }}</div>

            <div class="label">{{ numberToChinese(weightTime) }}磅重量：</div>
            <div class="weight-number previous-weight">
              {{ saveWeightToShow(baseOrder.weightOut || baseOrder.weightIn) }}
            </div>
          </div>
          <div class="row">
            <div class="label">
              <div class="red"></div>
              地磅读数：
            </div>
            <div class="weight-number disabled value">
              {{ saveWeightToShow(form.weight) }}
            </div>

            <van-checkbox
              v-model="form.notWeightOut"
              shape="square"
              label-position="right"
              @click="notWeightOutClick"
              :disabled="form.cusType === '1'"
            >
              无皮重
            </van-checkbox>
          </div>
          <div class="row">
            <div class="label">
              <div class="red">*</div>
              车牌号：
            </div>
            <input
              class="value"
              v-model="form.number"
              :disabled="form.notNumber || hasInspectData || hasPoundData"
            />
            <van-checkbox
              :disabled="hasInspectData || hasPoundData"
              v-model="form.notNumber"
              shape="square"
              label-position="right"
              @click="notNumberClick"
              >无车牌</van-checkbox
            >
          </div>
          <div class="row" v-show="inspectIndex === 2 || form.notWeightOut">
            <div class="label">
              <div class="red">*</div>
              库区：
            </div>

            <div
              class="value"
              :class="{
                placeholder: form.materialInfo[0].warehouseName === '',
                disabled: hasInspectData
              }"
              @click="showWarehouseSearch"
            >
              {{ form.materialInfo[0].warehouseName || '请选择库区' }}
            </div>
          </div>

          <div class="row" v-show="inspectIndex === 2 || form.notWeightOut">
            <div class="label">
              <div class="red">*</div>
              物料：
            </div>
            <div
              class="value"
              :class="{
                placeholder: form.materialInfo[0].materialName === '',
                disabled: hasInspectData
              }"
              @click="showMaterialSearch"
            >
              {{ form.materialInfo[0].materialName || '请选择物料' }}
            </div>
          </div>

          <div class="row" v-show="inspectIndex === 2 || form.notWeightOut">
            <div class="label">
              <div class="red">*</div>
              扣杂({{ weightUnit }})：
            </div>
            <input
              class="value"
              type="number"
              v-model="form.inspectImpurity"
              :disabled="hasInspectData"
            />
            <div class="label">
              <div class="red">*</div>
              单价(元/{{ weightUnit }})：
            </div>
            <input
              class="value"
              type="number"
              v-model="form.priceTaxOut"
              :disabled="hasInspectData"
              placeholder="-"
            />
          </div>
        </div>

        <div class="footer">
          <div class="btn cancel" @click="cancel" v-if="inspectIndex === 1">取消</div>
          <div class="btn cancel" @click="submit('1')" v-if="inspectIndex === 2">
            继续{{ form.cusType === '1' ? '装' : '卸' }}货
          </div>
          <div class="btn submit" @click="submit('2')">确认并过磅</div>
        </div>
      </div>
    </div>
  </div>
  <Search
    v-model:show="materialSearchShow"
    @change="materialChange"
    :searchLimit="{
      status: '3',
      materialType: form.materialInfo[0] ? form.materialInfo[0].materialType : ''
    }"
    type="material"
  >
  </Search>
  <Search
    v-model:show="warehouseSearchShow"
    @change="warehouseChange"
    :searchLimit="warehouseSearchLimt"
    type="warehouse"
  >
  </Search>
  <Search
    v-model:show="supplierSearchShow"
    @change="supplierChange"
    type="supplier"
    :addable="true"
  >
  </Search>
</template>

<script setup>
import api from '@/api/index'
import { ref, reactive, computed, onMounted } from 'vue'
import { showNotify, showToast } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import { upload } from '@/libs/ali'
import { useSystemStore } from '@/stores/system'
import Search from '@/components/Search.vue'
import {
  getWeightUnit,
  saveWeightToShow,
  savePriceToShow,
  inputPriceToSave,
  inputWeightToSave
} from '@/libs/unit'
import { numberToChinese } from '@/libs/utils'
import qrCode from '@/assets/img/qr-code-white.svg'
import face from '@/assets/img/face-white.svg'
import idCard from '@/assets/img/id-card-white.svg'
import retail from '@/assets/img/retail-white.svg'
const weightUnit = getWeightUnit()
const systemStore = useSystemStore()
const form = reactive({
  id: '',
  cusId: '',
  code: '',
  dbName: 'cusp',
  imageUrl: '',
  cusIdCard: '',
  cusTaxNum: '',
  cusMobile: '',
  cusName: '',
  cusType: '',
  type: '1',
  weight: '',
  weightPics: '',
  inspectImpurity: '0',
  priceTaxOut: '',
  materialInfo: [
    {
      warehouseId: '',
      warehouseName: '',
      storehouseId: '',
      storehouseName: '',
      materialType: '',
      materialId: '',
      materialNo: '',
      materialName: '',
      materialProperty: ''
    }
  ],
  number: localStorage.ocrCarNumber || '无车牌',
  notNumber: localStorage.ocrCarNumber ? false : true,
  notWeightOut: false,
  unload: ''
})
const formForInit = JSON.parse(JSON.stringify(form))
const showIdCard = computed(() => {
  if (form.cusIdCard) {
    return form.cusIdCard.substring(0, 5) + '********' + form.cusIdCard.substring(15)
  } else {
    return ''
  }
})

const file1 = ref('')
const file2 = ref('')
const file3 = ref('')
const isRecognitionSuccessful = ref(false)
const inspectIndex = ref(1)
let json
const codeType = ref('')
const warehouseSearchLimt = ref({})
let baseOrder = reactive({})
const hasInspectData = ref(false)
const hasPoundData = ref(false)
let captureKey = ''
const typeImg = ref('')
const weightTime = ref(0)
const route = useRoute()
onMounted(async () => {
  isRecognitionSuccessful.value = route.query.isRecognitionSuccessful === 'true'
  inspectIndex.value = Number(route.query.inspectIndex)
  captureKey = route.query.captureKey
  const inspectData = window.android.getInspectData()
  json = JSON.parse(inspectData)
  file1.value = 'data:image/jpeg;base64,' + json.file1
  file2.value = 'data:image/jpeg;base64,' + json.file2
  file3.value = 'data:image/jpeg;base64,' + json.file3 || ''
  form.weight = Number(json.weight)
  form.code = json.code
  form.cusIdCard = json.code
  form.type = json.type
  codeType.value = json.codeType

  //客商信息 如果是车牌识别进来的 就会请求接口获取
  let cus
  if (route.query.cusMsg) {
    cus = JSON.parse(route.query.cusMsg)
  }
  if (inspectIndex.value == 2) {
    if (form.type === '4') {
      baseOrder = (await api.baseOrderDetail({ id: route.query.baseOrderId })).data
    } else if (form.type === '6') {
      baseOrder = (await api.baseOrderDetail({ id: json.code })).data
      cus = (
        await api.cusDetail({
          id: baseOrder.flow === '1' ? baseOrder.supplierId : baseOrder.customerId
        })
      ).data
      form.type = baseOrder.extend4
    } else {
      baseOrder = (await api.cusBaseOrders({ cusId: cus.cusId })).data
    }
    form.id = baseOrder.id
    weightTime.value = baseOrder.materialInfo.length + 1
    if (baseOrder.process === '3') {
      hasInspectData.value = true
      for (const key in form.materialInfo[0]) {
        if (baseOrder[key]) {
          form.materialInfo[0][key] = baseOrder[key]
        }
      }
      form.number = baseOrder.number
      form.priceTaxOut = savePriceToShow(baseOrder.priceTaxOut)
      form.inspectImpurity = saveWeightToShow(baseOrder.inspectImpurity)
      form.notNumber = baseOrder.notNumber === '1'
      form.notWeightOut = baseOrder.notWeightOut === '1' || baseOrder.notWeightOut === '2'
    } else {
      form.notNumber = baseOrder.notNumber === '1'
      form.number = baseOrder.number
      if (baseOrder.number && baseOrder.number !== '无车牌') {
        hasPoundData.value = true
      }
    }
  }
  switch (form.type) {
    case '1':
      typeImg.value = qrCode
      break
    case '2':
      typeImg.value = face
      break
    case '3':
      typeImg.value = idCard
      break
    case '4': {
      typeImg.value = retail
      const cus = JSON.parse(route.query.cusMsg)
      form.cusName = cus.cusName
      break
    }
    case '5':
      typeImg.value = idCard
      break
  }
  // 1收货2发货
  let defaultMaterial = systemStore.defaultMaterialSh
  if (isRecognitionSuccessful.value) {
    form.cusId = cus.cusId
    form.cusName = cus.cusName
    form.cusMobile = cus.cusMobile
    form.cusIdCard = cus.cusIdCard
    form.cusTaxNum = cus.cusTaxNum
    // 1客户2供应商
    form.cusType = cus.cusType
    defaultMaterial =
      cus.cusType === '1' ? systemStore.defaultMaterialFh : systemStore.defaultMaterialSh
  }
  form.materialInfo[0] = defaultMaterial
})
const supplierSearchShow = ref(false)
function showSupplierSearch() {
  if (form.type !== '4') {
    return
  }
  if (supplierSearchShow.value) {
    return
  }
  supplierSearchShow.value = true
}
const supplierChange = (item) => {
  if (typeof item === 'string') {
    form.cusName = item
  } else {
    form.cusId = item.id
    form.cusName = item.cusName
    form.cusIdCard = item.cusIdCard
    form.cusMobile = item.cusMobile
  }
}
const warehouseSearchShow = ref(false)
function showWarehouseSearch() {
  if (hasInspectData.value) {
    return
  }
  warehouseSearchShow.value = true
}
const warehouseChange = (item) => {
  form.materialInfo[0].warehouseId = item.id
  form.materialInfo[0].warehouseName = item.warehouseName
  form.materialInfo[0].materialType = item.warehouseType
  form.materialInfo[0].storehouseId = item.storehouseId
  form.materialInfo[0].storehouseName = item.storehouseName
}
const materialSearchShow = ref(false)
function showMaterialSearch() {
  if (hasInspectData.value) {
    return
  }
  materialSearchShow.value = true
}
const materialChange = (item) => {
  form.materialInfo[0].materialId = item.id
  form.materialInfo[0].materialName = item.materialName
  form.materialInfo[0].materialNo = item.materialNo
  form.materialInfo[0].materialProperty = item.materialProperty
}

const cancel = () => {
  window.android.faceCancel()
}

const router = useRouter()
const submit = async (unload) => {
  if (inspectIndex.value === 1) {
    if (!form.cusName) {
      showNotify({
        type: 'danger',
        message: '请填写名称'
      })
      return
    }
  }
  if (inspectIndex.value === 2) {
    if (!form.notNumber && !form.number) {
      showNotify({
        type: 'danger',
        message: '请填写车牌'
      })
      return
    }
    if (!form.materialInfo[0].warehouseName) {
      showNotify({
        type: 'danger',
        message: '请选择库区'
      })
      return
    }
    if (!form.materialInfo[0].materialName) {
      showNotify({
        type: 'danger',
        message: '请选择物料'
      })
      return
    }
    if (form.inspectImpurity === '') {
      showNotify({
        type: 'danger',
        message: '请填写扣杂'
      })
      return
    }
  }
  const capture = window.android.captureWebview()
  const toast = showToast({
    type: 'loading',
    message: '提交中',
    forbidClick: true,
    overlay: true,
    duration: 0
  })
  try {
    if (!captureKey && json.capture) {
      captureKey = await upload(json.capture)
    }
    form.imageUrl = `${import.meta.env.VITE_INNER_FILE_DOMAIN}${captureKey}`
    form.weightPics = `${await upload(json.file1)},${await upload(json.file2)},${json.file3 ? await upload(json.file3) : ''},${await upload(capture)}`
    const temp = JSON.parse(JSON.stringify(form))
    temp.unload = unload
    temp.notNumber = temp.notNumber ? '1' : '0'
    temp.notWeightOut = temp.notWeightOut ? inspectIndex.value + '' : '0'
    temp.priceTaxOut = inputPriceToSave(temp.priceTaxOut)
    temp.inspectImpurity = inputWeightToSave(temp.inspectImpurity)
    if (inspectIndex.value === 1) {
      const res = await api.weightInBaseOrderYtj(temp)
      window.android.tts('操作成功')
      if (temp.notWeightOut !== '0') {
        router.push({
          path: '/WeightSuccess',
          query: {
            id: res.data
          }
        })
      } else {
        window.android.faceCancel()
      }
    } else {
      await api.weightOutBaseOrderYtj(temp)
      window.android.tts('操作成功')
      if (unload === '2') {
        router.push({
          path: '/WeightSuccess',
          query: {
            id: form.id
          }
        })
      } else {
        window.android.faceCancel()
      }
    }
    localStorage.ocrCarNumber = ''
  } finally {
    toast.close()
  }
}

function notNumberClick() {
  if (form.notNumber) {
    form.number = '无车牌'
  } else {
    form.number = ''
  }
}

function notWeightOutClick() {
  if (!form.notWeightOut && inspectIndex.value === 1) {
    const tempForm = JSON.parse(JSON.stringify(formForInit))
    form.notNumber = tempForm.notNumber
    form.number = tempForm.number
    form.materialInfo = tempForm.materialInfo
    form.inspectImpurity = tempForm.inspectImpurity
    form.priceTaxOut = tempForm.priceTaxOut
  }
}
</script>

<style lang="scss">
@import url('@/assets/style/mixins.scss');
@media screen and (max-width: 1080px) {
  .confirm-weight {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    input:disabled {
      background-color: #eeeeee;
    }
    .body {
      flex: 1;
      height: 0;
      overflow-y: auto;
      display: flex;
      flex-direction: column;
      .cus-msg {
        width: 100%;
        display: flex;
        flex-direction: column;
        .content {
          display: flex;
          flex-direction: row;
          margin: 0 0.2rem;
          .capture {
            width: 95.7px;
            height: 117.8px;
            padding: 0 0.2rem 0 0;
            border-radius: 2px;
          }
          .msg {
            width: 0;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            .row {
              display: flex;
              flex-direction: row;
              font-size: 0.4rem;
              justify-content: space-around;
              height: 30px;
              .label {
                display: flex;
                width: 1.9rem;
                align-items: center;
                justify-content: center;
                .red {
                  width: 0.1rem;
                  margin-right: 0.1rem;
                  color: red;
                  display: flex;
                  align-items: center;
                }
              }
              .value {
                // border: none;
                border: 1px solid #cccccc;
                flex: 1;
                width: 0;
                height: 24.5px;
                padding: 0 0 0 0.1rem;
              }
            }
          }
        }

        .capture-container {
          margin: 0 0.2rem;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          .weight-pic {
            width: 170px;
            height: 100px;
            border-radius: 2px;
          }
        }
      }
      .other {
        width: 100%;
        height: 0;
        display: flex;
        flex-direction: column;
        flex: 1;
        .weight {
          display: flex;
          flex-direction: column;
          padding: 0 0.2rem;
          flex: 1;
          .row {
            display: flex;
            font-size: 0.4rem;
            height: 30px;
            align-items: center;
            justify-content: space-around;
            .label {
              min-width: 2rem;
              display: flex;
              align-items: center;
              justify-content: center;
              .red {
                color: red;
                // width: 0.1rem;
              }
            }

            .value {
              // border: none;
              border: 1px solid #cccccc;
              flex: 1;
              width: 0;
              height: 24.5px;
              line-height: 24.5px;
              padding: 0 0 0 0.1rem;
            }
            .value.placeholder {
              color: #777;
            }
            .disabled {
              background-color: #eee;
            }
            .van-checkbox {
              margin-left: 0.2rem;
            }
            .weight-number {
              font-weight: bold;
              font-size: 35px;
              padding: 4px 0;
              flex: 1;
              display: flex;
              justify-content: center;
            }
            .weight-number + .label {
              margin-left: 8px;
            }
            .no {
              border: none;
              font-weight: normal;
            }
            .previous-weight {
              flex: none;
            }
          }
          .row + .row {
            margin-top: 0.1rem;
          }
        }
      }
    }
    .btn-container {
      display: flex;
      flex-direction: row;
      width: 100%;
      height: 45px;
      .btn {
        flex: 1%;
        height: 100%;
        font-size: 0.5rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid #000000;
        background-color: #ffffff;
      }
      .btn.submit {
        border-color: #1685fe;
        background-color: #1685fe;
        color: #ffffff;
      }
    }
  }
}
@media screen and (min-width: 1920px) {
  .confirm-weight {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    .van-checkbox {
      margin-left: 2px;
      .van-checkbox__icon {
        height: auto;
        font-size: 2px;
        .van-icon {
          width: 12px;
          height: 12px;
          border-width: 0.5px;
          line-height: 12px;
          font-size: 8px;
        }
      }
      .van-checkbox__label {
        margin-left: 2px;
      }
    }
    input:disabled {
      background-color: #eeeeee;
    }
    .body {
      flex: 1;
      height: 0;
      overflow-y: auto;
      display: flex;
      flex-direction: row;
      .cus-msg {
        width: 0;
        height: 100%;
        flex: 1;
        display: flex;
        flex-direction: column;
        margin: 0 2px;
        .content {
          display: flex;
          flex-direction: row;
          height: 65px;

          .capture {
            width: 45px;
            height: 100%;
            padding: 0 2px 0 0;
            border-radius: 2px;
          }
          .msg {
            width: 0;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            .row {
              display: flex;
              flex-direction: row;
              font-size: 9px;
              justify-content: space-around;
              height: 16px;
              .label {
                display: flex;
                width: 40px;
                align-items: center;
                justify-content: center;
                .red {
                  width: 1px;
                  margin-right: 4px;
                  color: red;
                  display: flex;
                  align-items: center;
                }
              }
              .value {
                // border: none;
                border: 0.5px solid #cccccc;
                flex: 1;
                width: 0;
                height: 100%;
                padding: 0 0 0 1px;
              }
            }
          }
        }

        .capture-container {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          .weight-pic {
            width: 83px;
            height: 59px;
            border-radius: 2px;
          }
        }
      }
      .split {
        width: 1px;
        background-color: #1e98d7;
        margin: 7px 0;
        align-self: stretch;
      }
      .other {
        width: 0;
        height: 100%;
        flex: 1;
        display: flex;
        flex-direction: column;
        flex: 1;
        margin: 0 8px;
        .weight {
          display: flex;
          flex-direction: column;
          flex: 1;
          .row {
            display: flex;
            font-size: 9px;
            height: 16px;
            align-items: center;
            justify-content: space-around;
            .label {
              min-width: 45px;
              display: flex;
              align-items: center;
              justify-content: start;
              .red {
                color: red;
                // width: 0.1rem;
              }
            }

            .value {
              // border: none;
              border: 0.5px solid #cccccc;
              flex: 1;
              width: 0;
              height: 100%;
              padding: 0 0 0 1px;
              word-wrap: break-word;
            }
            .value.placeholder {
              color: #777;
            }
            .disabled {
              background-color: #eee;
            }
            .van-checkbox {
              margin-left: 0.2rem;
            }
            .weight-number {
              font-weight: bold;
              font-size: 15px;
              flex: 1;
              display: flex;
              justify-content: center;
            }
            .weight-number + .label {
              margin-left: 8px;
            }
            .no {
              border: none;
              font-weight: normal;
              display: flex;
              align-items: center;
            }
            .previous-weight {
              flex: none;
            }
          }
          .row + .row {
            margin-top: 0.1rem;
          }
        }
      }
    }
    .btn-container {
      display: flex;
      flex-direction: row;
      width: 100%;
      height: 45px;
      .btn {
        flex: 1%;
        height: 100%;
        font-size: 0.5rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid #000000;
        background-color: #ffffff;
      }
      .btn.submit {
        border-color: #1685fe;
        background-color: #1685fe;
        color: #ffffff;
      }
    }
  }
}
</style>
